package site.thatime.fnp;

import java.util.Collection;
import java.util.Map;

import io.flutter.plugin.common.MethodCall;
import top.someapp.applib.Base;

/**
 * @author zwz
 * @date 2019-10-23
 */
final class MethodCallAdapter implements Base.MethodCallInfo {
    final String mClassName;
    final String mMethodName;
    private final MethodCall mMethodCall;
    private final Map<String, ?> mParams;

    MethodCallAdapter(String className, String methodName, MethodCall methodCall) {
        this(className, methodName, methodCall, null);
    }

    MethodCallAdapter(String className, String methodName, MethodCall methodCall, Map<String, ?> params) {
        mClassName = className;
        mMethodName = methodName;
        mMethodCall = methodCall;
        mParams = params;
    }

    private boolean isMethodCall() {
        return mMethodCall != null;
    }

    @Override
    public String className() {
        return mClassName;
    }

    @Override
    public String methodName() {
        return mMethodName;
    }

    @Override
    public boolean hasArgument(String key) {
        if (isMethodCall())
            return mMethodCall.hasArgument(key);
        return mParams != null && mParams.containsKey(key);
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T argument(String key) {
        if (isMethodCall())
            return mMethodCall.argument(key);
        return mParams == null ? null : (T) mParams.get(key);
    }

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, ?> namedArguments() {
        return isMethodCall() ? (Map<String, Object>) mMethodCall.arguments : mParams;
    }

    @Override
    public Object[] ordinalArguments() {
        if (isMethodCall()) {
            Object args = mMethodCall.arguments;
            if (args == null)
                return null;

            Object[] arguments;
            if (args instanceof Object[]) {
                arguments = (Object[]) args;
            } else if (args instanceof Collection) {
                Collection collection = (Collection) args;
                arguments = new Object[collection.size()];
                int i = 0;
                for (Object e : collection) {
                    arguments[i++] = e;
                }
            } else {
                arguments = new Object[]{args};
            }

            return arguments;
        }
        return mParams == null ? null : mParams.values().toArray();
    }
}
